package org.ielts.action.base;

import java.util.List;

import org.ielts.action.BaseAction;
import org.ielts.domain.base.Campus;
import org.ielts.domain.base.Classroom;
import org.ielts.service.CampusService;
import org.ielts.service.ClassroomService;
import org.junit.runners.Parameterized.Parameters;
import org.springframework.beans.factory.annotation.Autowired;

import static com.yifeng.struts2.RequestParameters.*;
import static com.yifeng.struts2.ResultParameters.*;
import static com.yifeng.struts2.ResultConstants.*;
import static com.yifeng.struts2.ActionUtils.*;
import com.yifeng.modules.annotations.Operation;
import com.yifeng.struts2.action.FormAction;
import com.yifeng.utils.JsonResultBuilder;

public class ClassroomAction extends BaseAction {

	@Autowired
	ClassroomService classroomService;

	@Autowired
	CampusService campusService;

	@Operation(result = FILL)
	public String listClassroom() {

		Iterable<Classroom> classrooms = classroomService.findAll();
		put("classrooms", classrooms);

		Iterable<Campus> campuses = campusService.findAll();
		put("campuses", campuses);

		return FILL;
	}

	@Operation(result = JSON)
	public String doCreateClassroom() {
		String name = form.readString("name");
		String campus = form.readString("campus");

		Classroom classroom = classroomService.findByNameAndCampus(name, campus);
		if (classroom != null) {
			setJson(JsonResultBuilder.success(false).msg("同校区已存在同名的教室").json());

			return JSON;
		}

		classroomService.createClassroom(name, campus);

		setJson(JsonResultBuilder.success(true).msg("创建教室成功").json());
		return JSON;
	}

	@Operation(result = JSON)
	public String doRemoveClassroom() {
		String id = form.readString("id");

		classroomService.removeClassroom(id);

		setJson(JsonResultBuilder.success(true).msg("删除教室成功").json());
		return JSON;
	}

	@Operation(result = JSON)
	public String doModifyClassroom() {
		String id = form.readString("id");
		String name = form.readString("name");
		String campus = form.readString("campus");

		Classroom classroom = classroomService.findByNameAndCampus(name, campus);
		if (classroom != null && !classroom.getId().equals(id)) {
			setJson(JsonResultBuilder.success(false).msg("同校区已存在同名的教室").json());

			return JSON;
		}

		classroomService.modifyClassroom(id, name, campus);

		setJson(JsonResultBuilder.success(true).msg("修改教室成功").json());
		return JSON;
	}
}
